const _ = require('lodash')
const Eta = require('eta')
const { join } = require('path')
const { getFileContent } = require('./files')
const { translate } = require('./translators/entityConfig')

const initConfig = {
	companyName: 'ChenXin',
	projectName: 'SmartCanteen',
	corePath: 'aspnet-core',
	coreSrcPath: 'src',
	domainPath: '<%=it.companyName%>.<%=it.projectName%>.Domain',
	domainSharedPath: '<%=it.companyName%>.<%=it.projectName%>.Domain.Shared',
	localizationPath: 'Localization/<%=it.projectName%>',
	applicationPath: '<%=it.companyName%>.<%=it.projectName%>.Application',
	applicationPathAutoMapperProfile: '<%=it.projectName%>ApplicationAutoMapperProfile',
	applicationContractsPath: '<%=it.companyName%>.<%=it.projectName%>.Application.Contracts',
	entityFrameworkCorePath: '<%=it.companyName%>.<%=it.projectName%>.EntityFrameworkCore',
	dbContextPath: 'EntityFrameworkCore',
	dbContextName: '<%=it.projectName%>DbContext',
	dbContextAnchor: 'public DbSet<AppUser> Users { get; set; }',
	dbContextModelCreatingExtensionsName: '<%=it.projectName%>DbContextModelCreatingExtensions',
	dbContextModelCreatingExtensionsAnchor: '/* Configure your own tables/entities inside here */',
	hostPath: '<%=it.companyName%>.<%=it.projectName%>.HttpApi.Host',
	vuePath: 'vue',
	vueSrcPath: 'src',
	vueApiPath: 'api',
	vueViewsPath: 'views',
	vueRouterPath: 'router',
}

const getConfig = () => {
	console.log('✨ try to', 'read'.yellow, 'config.json'.green, 'from directory', `"${__dirname}"`.underline)

	const configPath = join(__dirname, 'config.json')
	const configContent = getFileContent(configPath)

	const config = Object.assign(initConfig, JSON.parse(configContent))

	// 把特殊的配置再解析一次, eg: domainPath: '<%=it.companyName%>.<%=it.projectName%>.Domain' => domainPath: 'ChenXin.SmartCanteen.Domain'
	const commonConfig = {}
	const specialConfig = {}

	_.forIn(config, (val, key) => {
		if (val.indexOf('<%') > -1) {
			specialConfig[key] = val
		} else {
			commonConfig[key] = val
		}
	})

	_.forIn(specialConfig, (val, key) => {
		specialConfig[key] = Eta.render(val, commonConfig)
	})

	return Object.assign(commonConfig, specialConfig)
}

const getEntityConfig = (entityName) => {
	console.log('✨ try to', 'read'.yellow, `${entityName}.json`.green, 'from directory', `"${__dirname}\\entities"`.underline)

	const configPath = join(__dirname, `entities/${entityName}.json`)

	const config = JSON.parse(getFileContent(configPath))

	translate(config)

	return config
}

module.exports = {
	getConfig,
	getEntityConfig,
}
